﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Net;
using System.Diagnostics;

namespace WebcamHttp
{
    class CameraFrame
    {

        public Image LastImage {get; set;}

        public static CameraFrame GetNextFrame(string url)
        {
            try
            {
                WebRequest req = HttpWebRequest.Create(url);
                WebResponse resp = req.GetResponse();

                if (resp.ContentType != "image/jpeg")
                    return null;

                var timeStr = resp.Headers["Date"];
                DateTime pictureTime = DateTime.Parse(timeStr);

                var respstr = resp.GetResponseStream();

                int length = (int)resp.ContentLength;
                var buffer = new byte[length];

                //int br = respstr.Read(buffer, 0, length);
                //Debug.Assert(br == length, String.Format("ContentLength: {0}, Read length: {1}", length, br));

                Image bmp = Bitmap.FromStream(respstr);
                respstr.Close();

                return new CameraFrame() { LastImage = bmp };
            }
            catch
            {
                return null;
            }
        }

    }
}
